/*
 *    Thing Game Library
 *   Copyright (C)2005 - 2010 Eduardo Nunes Pereira (eduardonunesp at gmail dot com)
 *
 *   This program/library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 *   This program/library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 *    You should have received a copy of the GNU Lesser General Public
 * License along with this program/library ; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "VideoManager.hpp"
#include "Globals.hpp"
#include "Surface.hpp"
#include "Logger.hpp"

Thing::Video::VideoManager::VideoManager():
    _screen(NULL) {}

Thing::Video::VideoManager::~VideoManager()
{
    DBG("Cleaning video");
    delete _screen;
}

void Thing::Video::VideoManager::initialize(const Thing::Video::VideoMode& vmode)
{
    DBG("Trying to initialize video");

    if(SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        throw VideoException(VideoException::UNINITIALIZED_VIDEO, "Error while SDL_Init");
    }

    SDL_Rect** modes;

    modes = SDL_ListModes(NULL, vmode.flags);

    if (modes == (SDL_Rect**)0) 
    {
        throw VideoException(VideoException::VIDEO_MODES_UNAVAIBLE, "No video mode avaible"); 
    }

    if (modes == (SDL_Rect**)-1) {
        DBG("All resolutions avaible");
    }
    else
    {
        for (int i = 0; modes[i]; ++i)
        {
            DBG(STG(FMT("Mode %d x %d") % modes[i]->w % modes[i]->h));
        }
    }

    DBG("Setting video mode");

    _screen = new Surface(SDL_SetVideoMode(vmode.width, vmode.height, vmode.res, vmode.flags));

    if(!_screen)
    {
        throw VideoException(VideoException::NULL_SCREEN_SURFACE, "Cannot initialize screen surface");
    }

    DBG("Video initialized");
}

void Thing::Video::VideoManager::update()
{
    if(Flag::SOFT_RENDER)
        _screen->SoftRender();
    else
        _screen->HardRender();
}
